import sys
import warnings
warnings.filterwarnings('ignore')
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, re
from urllib.parse import urlencode
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "天地关爱百万医疗（2019个人版）"

    # 生产产品数据
    def genProductInfo(self):
        plan = {
            # 年龄段
            "year": ["0-4", "5-10", "11-15", "16-20", "21-25", "26-30", "31-35", "36-40", "41-45", "46-50", "51-55",
                     "56-60"],
            # 有无社保
            "socialSec": ["Y", "N"],
            # 保障期限
            "expire": ["1年"],
            # 交费方式
            "payType": ["年交"],
            # 一般医疗保险金额
            "generalMedical": ["3000000"],
            # 恶性肿瘤医疗保险金额
            "cancerMedical": ["3000000"],
            # 飞机意外伤害
            "accidentPlane": ["1000000"],
            # 火车意外伤害
            "accidentTrain": ["100000"],
            # 轮船意外伤害
            "accidentShip": ["100000"],
            # 汽车意外伤害
            "accidentPassenger": ["100000"],
            # 质子重离子治疗费用
            "extSerious": ["0", "1000000"],
            # 恶性肿瘤和10种重大手术特需病房 0 不投保 1 投保
            "importWard": ["0", "1"]
        }
        for v in product(plan["year"], plan["socialSec"], plan["expire"], plan["payType"], plan["generalMedical"], plan["cancerMedical"], plan["accidentPlane"], plan["accidentTrain"], plan["accidentShip"],
                         plan["accidentPassenger"], plan["extSerious"], plan["importWard"]):
            data = Helper.formatProductInfo( plan,v )
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format( **data ))
            self.mysql._conn.commit()
            print( domain[self.name]["insert_sql"].format( **data ) )

    #执行爬虫
    def requestJson(self,dt=None):

        code = "1" if dt["year"] == "0-4" else str(int(int(dt["year"].split("-")[1])/5))
        data = {

            "productCode": "WTH_GR2019 - N_"+code+"" ,
            "yiparam": "yiyesno" if dt["importWard"] == "0" else "yiyes",
            "zhiparam": "zhiyesno" if dt["extSerious"] == "0" else "zhiyes",
            "age": dt["year"].split("-")[1],
            "_action": "commonCalculateFee2"
        }
        payload = urlencode(data).replace("+","")
        r = requests.post( url = domain[self.name]["url"], headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200:
            price = re.search(r"'SUM_PREMIUM':'(.*)',", r.text).group(1)
            price = Helper.decimalParse(price)
            data = {
                "name": self.name,
                "id": dt["id"],
                "price": price
            }
            print( data )
            self.mysql.updatePrice(data)
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)
            print("\n/*更新产品价格数据失败:%d*/" % dt["id"])

    def main(self):
        
        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)
            self.requestJson(dt)
